﻿using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using MusicFluent.Controls;
using MusicFluent.Models;
using MusicFluent.Views;
using NetEasyMusic.Lib.Data;

namespace MusicFluent.Pages;

public partial class LoginView : UserControl
{
    public LoginView()
    {
        Login = new Login();
        InitializeComponent();
    }

    private Login Login { get; }

    protected override async void OnInitialized()
    {
        try
        {
            QrCordImage.Source = new Bitmap(new MemoryStream(await Login.QrLogin()));
        }
        catch
        {
            Content = new NetErrorControl();
        }
    }

    private async void QrOkClick(object? sender, RoutedEventArgs e)
    {
        var s = await Login.Check();
        if (string.IsNullOrEmpty(s)) return;
        var window = ViewOpera.GetView<MainWindow>(Parent);
        if (window == null) return;
        window.Login(s);
        var context = new SettingModel { Cookie = s };
        context.Save();
    }

    private async void Flushed(object? sender, RoutedEventArgs e)
    {
        var bytes = await Login.QrLogin();
        QrCordImage.Source = new Bitmap(new MemoryStream(bytes));
    }

    private async void VisitorClick(object? sender, RoutedEventArgs e)
    {
        var a = await Login.Visitor();
        var window = ViewOpera.GetView<MainWindow>(Parent);
        if (window == null) return;
        window.Login(a);
        var context = new SettingModel { Cookie = a };
        context.Save();
    }

    private async void PhoneLoginClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(PhoneBox.Text) || string.IsNullOrEmpty(PasswordBox.Text)) return;
        var s = await Login.PhoneLogin(PhoneBox.Text, PasswordBox.Text);
        var window = ViewOpera.GetView<MainWindow>(Parent);
        window?.Login(s.Item1, s.Item2);
        var context = new SettingModel { Cookie = s.Item1 };
        context.Save();
    }

    private async void MailLoginClick(object? sender, RoutedEventArgs e)
    {
        if (string.IsNullOrEmpty(MailBox.Text) || string.IsNullOrEmpty(MailPasswordBox.Text)) return;
        var s = await Login.MailLogin(MailBox.Text, MailPasswordBox.Text);
        var window = ViewOpera.GetView<MainWindow>(Parent);
        window?.Login(s);
        var context = new SettingModel { Cookie = s };
        context.Save();
    }
}